package servlet;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.UploadFile;
import dto.DataManager;

import model.ProducerOwnCategory;
import model.Product;

/**
 * Servlet implementation class UpdateProduct
 */
@WebServlet("/UpdateProduct")
public class UpdateProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateProduct() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		DataManager dataManager = new DataManager();		
		Product product = new Product();
		
		ProducerOwnCategory poc = new ProducerOwnCategory();
		UploadFile.uploadFile(request, product, poc);
		product.setDateUpdated(Calendar.getInstance().getTime());
		
		if(product.getImage() == null) {
			product.setImage(dataManager.getProductById(product.getProductId()).getImage());
		}
		
		int producerOwnCategoryId;
		if((producerOwnCategoryId = dataManager.isHaveProducerOwnCategory(poc.getProducerId(), poc.getCategoryId())) == 0) {
			dataManager.addProducerOwnCategory(poc.getProducerId(), poc.getCategoryId());
			producerOwnCategoryId = dataManager.getNewProducerOwnCategoryId();
		}
		
		product.setProducterOwnCategory(producerOwnCategoryId);
		dataManager.updateProductWithProductId(product);
		
		response.sendRedirect("/ECommerce/viewProductAdmin.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
